﻿using Api.Shared.Model.Common;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class AlarmController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly ILogger<AlarmController> logger;

        public AlarmController(
            [FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper,
            ILogger<AlarmController> logger
        )
        {
            this.helper = helper;
            this.logger = logger;
        }

        [HttpGet]
        public async Task<IActionResult> GetAlarms([FromQuery] QueryInfo queryInfo)
        {
            if (queryInfo.Pagenum <= 0)
            {
                return StatusCode(204, "Failed");
            }
            if (queryInfo.Pagesize <= 0)
            {
                return StatusCode(204, "Failed");
            }
            int totalNumber = 0;

            var exp = Expressionable.Create<MyAlarm>();

            exp.AndIF(
                !string.IsNullOrWhiteSpace(queryInfo.Query),
                x => x.AlarmMessage.Contains(queryInfo.Query)
            );

            exp.AndIF(queryInfo.DateStart != null, x => x.InsertTime > queryInfo.DateStart);

            exp.AndIF(queryInfo.DateEnd != null, x => x.InsertTime < queryInfo.DateEnd);

            exp.AndIF(
                queryInfo.DateEnd != null && queryInfo.DateStart != null,
                x => (x.InsertTime < queryInfo.DateEnd && x.InsertTime > queryInfo.DateStart)
            );

            var alarms = this
                .helper.Db.Queryable<MyAlarm>()
                .Where(exp.ToExpression())
                .ToPageList(queryInfo.Pagenum, queryInfo.Pagesize, ref totalNumber);

            //int maxPageCount = (int)Math.Ceiling((double)totalNumber / queryInfo.Pagesize);
            var resultData = new
            {
                total = totalNumber,
                pagenum = queryInfo.Pagenum,
                alarms = alarms
            };
            if (alarms.Count > 0)
            {
                return Ok(resultData);
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }
    }
}
